package com.yunc.common.exception;

import com.yunc.common.utils.BaseConstant;
import com.yunc.common.utils.R;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 自定义异常处理器
 * 
 * @author ruoyi
 */
@RestControllerAdvice
public class DefaultExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(DefaultExceptionHandler.class);
    
    /**
     * 权限校验失败
     */
    @ExceptionHandler(AuthorizationException.class)
    public R handleAuthorizationException(AuthorizationException e) {
        log.error(e.getMessage(), e);
        return R.error("您没有数据的权限，请联系管理员添加");
    }

    /**
     * token异常
     */
    @ExceptionHandler(IncorrectCredentialsException.class)
    public R handleIncorrectCredentialsException(IncorrectCredentialsException e) {
        log.error(e.getMessage(), e);
        return R.error(BaseConstant.OAUTH_CODE_ERROR, "token失效，请重新登录");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    public R handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return R.error("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public R notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        return R.error("运行时异常:" + e.getMessage());
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(UCException.class)
    public R handleUCException(UCException e){
        return R.error(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error("服务器错误，请联系管理员");
    }

    /**
     * 数据校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleBindException(MethodArgumentNotValidException e) {
        // ex.getFieldError():随机返回一个对象属性的异常信息。如果要一次性返回所有对象属性异常信息，则调用ex.getAllErrors()
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        /*StringBuilder sb = new StringBuilder();
        sb.append(fieldError.getField())
                .append("=[")
                .append(fieldError.getRejectedValue())
                .append("]")
                .append(fieldError.getDefaultMessage());*/
        return R.error(fieldError.getDefaultMessage());
    }
}
